package com.smugmugsoftware.airconcalc.advanced;


import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class AdvancedLocaleFragment extends Fragment implements LocaleFragmentInterface {

	private SharedPreferences prefs;
	
	private MainActivityInterface activity;
	private View thisView;
	private Building thisBuilding;
	
	private TextView usedLocale;
	private EditText latitude;
	private EditText externalTemp;
	private EditText dailyRange;
	
	private boolean somethingChanged;

	private Spinner tightness;

	public AdvancedLocaleFragment() {}

	public AdvancedLocaleFragment(Building building) {
		this.thisBuilding = building;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		prefs = getActivity().getSharedPreferences("config.dat", Context.MODE_PRIVATE);
		
		setRetainInstance(true);

		if (savedInstanceState != null && savedInstanceState.getParcelable("SAVED_BUILDING") != null) {
			thisBuilding = savedInstanceState.getParcelable("SAVED_BUILDING");
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			this.activity = (MainActivityInterface) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		thisView = inflater.inflate(R.layout.advanced_locale_editor_fragment, container, false);

		activity.displayInfoDialog(thisView.getContext(), InformationDialog.LOCALE_FIRST_RUN, "LOCALE_FIRST_RUN");
		
		TextWatcher customWatcher = new TextWatcher() {			
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s) {
				usedLocale.setText("CUSTOM");
				somethingChanged = true;
			}
		};
		
		TextWatcher somethingChangedWatcher = new TextWatcher() {			
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s) {
				somethingChanged = true;
			}
		};

		final EditText estimator = (EditText) thisView.findViewById(R.id.estimator);
		estimator.setText(thisBuilding.getEstimatorName());
		estimator.addTextChangedListener(somethingChangedWatcher);
		estimator.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus && estimator.getText().toString().length() == 0) {
					estimator.setText("(null)");					
				} else if (hasFocus && estimator.getText().toString().startsWith("(null)")) {
						estimator.setText("");
				}
			}
		});
		
		final EditText address = (EditText) thisView.findViewById(R.id.address);
		address.setText(thisBuilding.getAddress());
		address.addTextChangedListener(somethingChangedWatcher);
		address.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus && address.getText().toString().length() == 0) {
					address.setText("(null)");					
				} else if (hasFocus && address.getText().toString().startsWith("(null)")) {
					address.setText("");
				}
			}
		});
		
		ImageView localeHelp = (ImageView) thisView.findViewById(R.id.locale_help);
		localeHelp.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				activity.displayInfoDialog(thisView.getContext(), InformationDialog.LOCALE_HELP, null);
			}
		});
		
		usedLocale = (TextView) thisView.findViewById(R.id.using_locale);
		usedLocale.setText(thisBuilding.getLocaleName());
		
		int thisLatitude = thisBuilding.getActualLatitude();
		if (thisLatitude < 0) {
			thisLatitude = thisLatitude * -1;
		}
		latitude = (EditText) thisView.findViewById(R.id.latitude);
		latitude.setText(String.valueOf(thisLatitude));
		latitude.addTextChangedListener(customWatcher);
		
		final EditText designTemp = (EditText) thisView.findViewById(R.id.design_temp);
		designTemp.setText(String.valueOf(thisBuilding.getInternalTemp()));
		designTemp.addTextChangedListener(somethingChangedWatcher);
		
		externalTemp = (EditText) thisView.findViewById(R.id.external_temp);
		externalTemp.setText(String.valueOf(thisBuilding.getExternalDryBulb()));
		externalTemp.addTextChangedListener(customWatcher);

		dailyRange = (EditText) thisView.findViewById(R.id.daily_range_temp);
		dailyRange.setText(String.valueOf(thisBuilding.getDailyRangeInt()));
		dailyRange.addTextChangedListener(customWatcher);
		
		Button localeWizard = (Button) thisView.findViewById(R.id.locale_wizard_button);
		localeWizard.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				activity.displayLocaleDialog(thisView.getContext(), null);
			}
		});
		
		final Button northSouthButton = (Button) thisView.findViewById(R.id.latitude_ns_button);
		if (thisBuilding.getActualLatitude() >= 0) {
			northSouthButton.setText("N");
		} else {
			northSouthButton.setText("S");
		}
		
		northSouthButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (northSouthButton.getText().toString().equals("N")) {
					northSouthButton.setText("S");
					usedLocale.setText("CUSTOM");
					somethingChanged = true;
				} else if (northSouthButton.getText().toString().equals("S")) {
					northSouthButton.setText("N");
					usedLocale.setText("CUSTOM");
					somethingChanged = true;
				}
			}
		});

		tightness = (Spinner) thisView.findViewById(R.id.tightness_spinner);
		String[] tightnessStringList = getResources().getStringArray(R.array.construction_type);
		final ArrayAdapter<String> tightnessAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item);   
		tightnessAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		for (int i = 0; i < tightnessStringList.length; i++) {
			tightnessAdapter.add(tightnessStringList[i]);
		}
		tightness.setAdapter(tightnessAdapter);
		tightness.setSelection(thisBuilding.getConstructionTightness());
		
		ImageView cancelButton = (ImageView) thisView.findViewById(R.id.cancel_button);
		cancelButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (somethingChanged || tightness.getSelectedItemPosition() != thisBuilding.getConstructionTightness()) {
					activity.displayConfirmDialog(thisView.getContext(), ConfirmDialog.DISCARD_CHANGES, AdvancedRoomListFragment.LOCALE_EDITOR, 0);
				} else {
					activity.closeLocaleEditor(null);
				}
			}
		});
		
		ImageView saveButton = (ImageView) thisView.findViewById(R.id.save_button);
		saveButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				RelativeLayout latitudeWrapper = (RelativeLayout) thisView.findViewById(R.id.latitude_wrapper);
				RelativeLayout internalWrapper = (RelativeLayout) thisView.findViewById(R.id.design_temp_wrapper);
				RelativeLayout externalWrapper = (RelativeLayout) thisView.findViewById(R.id.external_temp_wrapper);
				RelativeLayout dailyRangeWrapper = (RelativeLayout) thisView.findViewById(R.id.daily_range_temp_wrapper);
				
				latitudeWrapper.setBackgroundResource(R.drawable.clear_error_background);
				internalWrapper.setBackgroundResource(R.drawable.clear_error_background);
				externalWrapper.setBackgroundResource(R.drawable.clear_error_background);
				dailyRangeWrapper.setBackgroundResource(R.drawable.clear_error_background);
				
				boolean fail = false;
				
				String[] strings = new String[3];
				int[] data = new int[5];
				
				strings[0] = estimator.getText().toString();
				if (strings[0] == null || strings[0].length() == 0) {
//					fail = true;
					strings[0] = "(null)";
				}
				
				strings[1] = address.getText().toString();
				if (strings[1] == null || strings[1].length() == 0) {
//					fail = true;
					strings[1] = "(null)";
				}

				strings[2] = usedLocale.getText().toString();
				if (strings[2] == null || strings[2].length() == 0) {
//					fail = true;
					strings[2] = "(null)";
				}
				
				String s = latitude.getText().toString();
				if (s == null || s.length() == 0) {
					fail = true;
					latitudeWrapper.setBackgroundResource(R.drawable.error_background);
				} else {
					try {
						data[0] = Integer.parseInt(s);
					} catch (Exception ex) {
						ex.printStackTrace();
						data[0] = 0;
					}
				}
				
				data[1] = zeroCheck(designTemp);
				data[2] = zeroCheck(externalTemp);
				data[3] = zeroCheck(dailyRange);
				data[4] = tightness.getSelectedItemPosition();
				
				if (northSouthButton.getText().toString().equals("S")) {
					data[0] = data[0] * -1;
				}
				
				if (data[1] == 0) {
					fail = true;
					internalWrapper.setBackgroundResource(R.drawable.error_background);
				}

				if (data[2] == 0) {
					fail = true;
					externalWrapper.setBackgroundResource(R.drawable.error_background);
				}

				if (data[3] == 0) {
					fail = true;
					dailyRangeWrapper.setBackgroundResource(R.drawable.error_background);
				}
				
				if (fail) {
					return;
				}

				thisBuilding.setGlobalValues(strings, data);
				activity.closeLocaleEditor(thisBuilding);
			}
		});

		return thisView;
	}
	
	public void cancelScreen() {
		if (somethingChanged || tightness.getSelectedItemPosition() != thisBuilding.getConstructionTightness()) {
			activity.displayConfirmDialog(thisView.getContext(), ConfirmDialog.DISCARD_CHANGES, AdvancedRoomListFragment.LOCALE_EDITOR, 0);
		} else {
			activity.closeLocaleEditor(null);
		}
	}

	public void returnFromConfirmDialog(int dialogType, int type, long id) {

		if (dialogType == ConfirmDialog.DISCARD_CHANGES) {
			activity.closeLocaleEditor(null);
		}
	}
	
	public void getLocaleData(double[] data, String[] returnList) {

		latitude.setText(String.valueOf((int) data[0]));
		externalTemp.setText(String.valueOf((int) data[3]));
		dailyRange.setText(String.valueOf((int) data[8]));
		usedLocale.setText(returnList[0]);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putParcelable("SAVED_BUILDING", thisBuilding);
	}
	
	protected int zeroCheck(EditText e) {
		String s = e.getText().toString();
		int returnDouble = 0;
		if (s == null || s.length() == 0 || Integer.valueOf(s) == 0) {
			return 0;
		} else {
			try {
				returnDouble = Integer.parseInt(s);
			} catch (Exception ex) {
				ex.printStackTrace();
				return 0;
			}
			return returnDouble;
		}
	}
}
